#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

int ticket=100;

void* Cow_cheap(void* arg)
{
  //黄牛抢票
  printf("我是 %p 线程，我现在要开始进行抢票任务啦！\n",pthread_self());
  pthread_mutex_t* mutex=(pthread_mutex_t*)arg;
  while(1){
    pthread_mutex_lock(mutex);//抢票之前先进行加锁
    if(ticket>0){
      printf("%p 抢到了 %d 号票！！\n",pthread_self(),ticket);
      ticket--;
      pthread_mutex_unlock(mutex);  //抢票结束进行解锁
    }
    else{
      //没票了
      printf("我是 %p 线程，现在没票了，我的任务结束了！\n",pthread_self());
      pthread_mutex_unlock(mutex);
      pthread_exit(NULL);      //线程退出
    }
    usleep(10);
  }
}


int main()
{
  pthread_mutex_t mutex;

  pthread_mutex_init(&mutex,NULL);  //初始化互斥锁

  //创建四个线程
  pthread_t tid[4];
  int i=0;
  for(i=0;i<4;++i){
      int ret = pthread_create(&tid[i],NULL,Cow_cheap,&mutex);
      if(ret!=0){
        perror("pthread_create error!\n");
        return -1;
      }
  }

  //线程等待
  for(i=0;i<4;++i){
    pthread_join(tid[i],NULL);
  }

  //线程结束之后进行锁的销毁
  pthread_mutex_destroy(&mutex);

  return 0;
}
